import { Context } from 'egg';

export default () => {
    return async function token(ctx: Context, next) {
        const urlArray: string[] = ['/api/admin/updateAdmin', '/api/admin/startAndStopAdmin', '/api/admin/createAdmin', '/api/admin/updateAdminPhone',
            '/api/department/updateDepartment', '/api/department/createDepartment', '/api/department/deleteDepartment', '/api/employee/updateEmployee',
            '/api/employee/deleteEmployee', '/api/employee/updateEmployeeStatus', '/api/employee/createEmployee', '/api/position/updatePosition',
            '/api/position/createPosition', '/api/position/deletePosition', '/api/project/updateProject', '/api/project/createProject', '/api/project/startAndStopProject',
            '/api/setting/settingRegisterStatus', '/api/workUnit/updateWorkUnit', '/api/workUnit/createWorkUnit', '/api/workUnit/deleteWorkUnit'];
        const token = ctx.headers.token;
        if (token && token.length > 0) {
            const admin: any = await ctx.service.adminService.searchAdminIdByToken(token);
            ctx.request.body.admin_id = admin.admin_id;
        }
        let url = ctx.originalUrl;
        let isNeedToken: boolean = true;
        for (const value of urlArray) {
            if (value === url) {
                const admin = await ctx.service.adminService.searchAdminByToken(token);
                if (admin) {
                    await next();
                    isNeedToken = false;
                    break;
                }
            }
        }
        if (!isNeedToken) {
            return;
        } else {
            await next();
        }
    };
};
